package com.sitech.openapi.componet;

import com.sitech.openapi.mapper.ProdPreOrderMapperService;
import com.sitech.openapi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SoapClientServiceImpl implements SoapClientService {

    @Autowired
    private ProdPreOrderMapperService prodPreOrderMapperService;

    @Override
    public String remoteSoapClientInfo(String url,String req) {

        log.info("==url===="+url+"============"+req);

        //设置请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "text/xml; charset=utf-8");
        httpHeaders.add("User-Agent", "Mozilla/4.0");
        httpHeaders.add("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
        httpHeaders.add("Accept-Encoding", "gzip, deflate");
        httpHeaders.add("Authorization", "");
        httpHeaders.add("SOAPAction", "http://servSys.mnp.sitech.com/IF/SendInfoTOdb");
        httpHeaders.add("Cache-Control", "no-cache");
        httpHeaders.add("Pragma", "no-cache");

        //设置请求体信息
        HttpEntity<String> requestEntity = new HttpEntity<String>(req, httpHeaders);

        //发送请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        String resMsg = response.getBody();

        log.info("==返回参数===="+resMsg);

        // TODO Auto-generated method stub
        return resMsg;
    }
    public void getElementList(Element element, Map<String, Object> tempMap, Map<String, String> respNs) throws Exception {

        List elements = element.elements();
        if (elements.size() == 0) {
            //没有子元素
            String respXml = element.getTextTrim();    // 返参xml
            String respPath = element.getUniquePath(); // 路径
            tempMap.put("respXml", respXml);
            tempMap.put("respPath", respPath);

            int leafNodeNum = (Integer) tempMap.get("leafNodeNum");
            leafNodeNum++;
            tempMap.put("leafNodeNum", leafNodeNum);    //叶子节点的

            if (log.isDebugEnabled()) {
                log.info("Soap报文中的返参为 : " + respXml);
            }
        } else {
            //有子元素
            for (Iterator it = elements.iterator(); it.hasNext(); ) {
                Element elem = (Element) it.next();

                //记录命名空间
                this.addNameSpace(elem, respNs);

                if ("Fault".equals(elem.getName())) {
                    throw new RuntimeException("soap中出现 Fault");
                }
                //递归遍历
                getElementList(elem, tempMap, respNs);
            }
        }
    }

    public Map<String, String> addSoapNameSpace(String soapNameSpace) {
        Map<String, String> soapNameSpaceMap = new HashMap<String, String>(2);
        if (soapNameSpace == null || ("").equals(soapNameSpace)) {
            soapNameSpaceMap.put("soap", "http://schemas.xmlsoap.org/soap/envelope/");
        } else {
            int index = soapNameSpace.indexOf("->");
            if (index == -1) {
                soapNameSpaceMap.put("soap", soapNameSpace);
            } else {
                String soapName = soapNameSpace.substring(0, index);
                String soapUrl = soapNameSpace.substring(index + 2, soapNameSpace.length());
                soapNameSpaceMap.put(soapName, soapUrl);
            }
        }
        return soapNameSpaceMap;
    }

    private static String DEFAULT_PREFIX = "default";

    public void addNameSpace(Element elem, Map<String, String> respNs) {

        for (Object o : elem.declaredNamespaces()) {
            Namespace ns = (Namespace) o;
            if (("").equals(ns.getPrefix()) || null == ns.getPrefix()) {
                respNs.put(DEFAULT_PREFIX, ns.getURI());
            } else {
                respNs.put(ns.getPrefix(), ns.getURI());
            }
        }
    }

    @Override
    public String remoteSoapClientInfoIml(String soapName, String bodyStr,String url) {

        log.info("==url===="+bodyStr+"============"+bodyStr);
        //解决乱码问题
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        converterList.remove(1); //移除StringHttpMessageConverter
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converterList.add(1, converter); //convert顺序错误会导致失败
        restTemplate.setMessageConverters(converterList);

        //设置请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        Map inMap = new HashMap<>();
        inMap.put("paraTypeId", "300016");
        inMap.put("functionCode", "ems");
        List<HashMap> outList = (List<HashMap>)prodPreOrderMapperService.getHeaderByCfg(inMap);
        if(outList!=null && outList.size() > 0){
            for(HashMap<String,String> outMap:outList){
                String paraKey = StringUtil.obj2Str(outMap.get("PARA_VALUE_01"));
                String paraValue = StringUtil.obj2Str(outMap.get("PARA_VALUE_07"));
                if(StringUtil.isNotEmptyOrNull(paraKey)&&StringUtil.isNotEmptyOrNull(paraValue)){
                    httpHeaders.add(paraKey,paraValue);
                }
            }
        }else {
            throw new RuntimeException("未查询到ems接口报文头信息！");
        }

        //设置请求体信息
        HttpEntity<String> requestEntity = new HttpEntity<String>(bodyStr, httpHeaders);

        //发送请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

        String resMsg = response.getBody();

        log.info("==返回参数===="+resMsg);

        // TODO Auto-generated method stub
        return resMsg;
    }
}
